package keeto.com.vn.classified.ui;

import it.sephiroth.android.library.widget.AbsHListView;
import it.sephiroth.android.library.widget.AbsHListView.OnScrollListener;
import it.sephiroth.android.library.widget.HListView;

import java.util.ArrayList;
import java.util.Vector;

import com.androidquery.AQuery;
import com.androidquery.util.AQUtility;

import keeto.com.vn.classfied.model.RatingProduct;
import keeto.com.vn.classified.adapter.CommentViewAdapter;
import keeto.com.vn.classified.adapter.HomeProductAdapter;
import keeto.com.vn.classified.adapter.RatingProductAdapter;
import keeto.com.vn.classified.adapter.ViewPagerAdapterProduct;
import keeto.com.vn.classified.config.IConstant;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.network.entity.CommentEntity;
import keeto.com.vn.classified.network.entity.ListItemEntity;
import keeto.com.vn.classified.network.entity.RatingInfo;
import keeto.com.vn.classified.network.entity.RatingUserEntity;
import keeto.com.vn.classified.utils.StringUtilities;
import keeto.com.vn.classified.utils.UtilityListView;
import keeto.com.vn.classified.utils.Utils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
/*
 * product_cate_5
 */
public class IADetailProductActivity extends Activity implements IConstant,OnClickListener, OnPageChangeListener, OnTouchListener {
	private final static String ACTION_NEW_PRODUCT = "com.supersabona.im.ui.activity.ia.Product";
	private final static String EXTRA_ITEM = "Product";
	private final static String PRODUCT_KEY = "products";

	private	BuiltinServiceManager mBuiltinServiceManager = null;
	private BuiltinService builtservice = null;
	/*
	 * Content
	 */
	private ImageButton btnBack;
	private TextView tvTitle;
	private ImageView btnSearchGlobal;

	private ViewPager mViewPager;
	private TextView tv_name_product;
	private TextView tvreportViolations;
	private TextView tv_interested_product;
	private ImageView arrow_left_product;
	private ImageView arrow_right_product;
	private TextView tv_price_product;
	private TextView tv_product_type;
	private Button btn_share;
	private Button btn_info_product;
	private WebView tv_desc_info;
	private TextView tv_other_product;
	private ProgressBar pBar_Other;
	private HListView hListView_Other;
	private RatingBar rating_Product;
	private TextView tv_Sum_rating;
	private ListView lvRating;
	private ListView lvComment;
	private Button btn_view_all_cmt;
	private RatingBar rating_feedback;
	private EditText edt_title_feedback;
	private EditText edt_content_feedback;
	private Button btn_send_feedback;
	private TextView tv_view_product_by_seller;
	private ProgressBar pBar_product_by_seller;
	private HListView hList_product_by_seller;
	private ProgressBar mBar;
	private ScrollView mScrollView;
	private TextView tv_rate_feedback_shop;
	private View v_rate_feedback_shop;

	/*
	 * Controller
	 */
	private AQuery mQuery ;
	private String mAction;
	private Bundle extras;
	private String productId = UNINITIALIZED_STRING;
	private ListItemEntity mProduct;
	private String sellerUserName = UNINITIALIZED_STRING;
	private String sellerEmail = UNINITIALIZED_STRING;
	private String tittleProduct = UNINITIALIZED_STRING;
	private String sellerPhome = UNINITIALIZED_STRING;
	private String discount;
	private int discountValue = 0;

	private DetailListener mListener = new DetailListener();
	private static InUIThreadHandler mReturnCodeHandler = null;
	private ViewPagerAdapterProduct hightLightAdapter;
	private HomeProductAdapter Other_product_Adapter;
	private HomeProductAdapter Product_by_Seller_Adapter;
	private RatingProductAdapter ratingProductAdapter;
	private int position_img_product;
	private Handler handler_img_product = new Handler();
	private int PAGE_LIMIT=10;
	private int pageCount;
	private int pageNumberOtherProduct=1;
	private ArrayList<CommentEntity> commentList = new ArrayList<CommentEntity>();
	private ArrayList<CommentEntity> sub_commentList = new ArrayList<CommentEntity>();
	private ArrayList<CommentEntity> commentList_total = new ArrayList<CommentEntity>();
	private Vector<RatingProduct> ratingList = new Vector<RatingProduct>();
	private CommentViewAdapter commentProductAdapter = null;
	private String userName= null;
	float moveY = 0;
	private float oldTouchValue;
	private boolean commented = false;
	private boolean isFocus = false;
	private String NotInPCodes;
	private String authKey = null;

	private ArrayList<ListItemEntity> arrOtherProduct = new ArrayList<ListItemEntity>();
	private ArrayList<ListItemEntity> arrBySellerProduct = new ArrayList<ListItemEntity>();
	View footerView;
	private ProgressBar pb_pg_load_bottom;
	/*
	 * FloatingBar
	 */
	private LinearLayout llFloatingbar;
	private LinearLayout ll_fb_phone;
	private LinearLayout ll_fb_chat;
	private LinearLayout ll_fb_email;
	private Animation mAnimation;
	private Animation mAnimation1;
	private ProgressHandler progresshandler = new ProgressHandler();
	private Handler mHandler = new Handler();
	private ProgressDialog mProgressDialog;

	public static void actionLaunchProduct(Context context, ListItemEntity itemProduct) {
		Intent i = new Intent(context, IADetailProductActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setAction(ACTION_NEW_PRODUCT);
		i.putExtra(EXTRA_ITEM, itemProduct);
		context.startActivity(i);
	}
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.ia_detail_product);
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(IADetailProductActivity.this);
		builtservice = mBuiltinServiceManager.getBuitinService();
		mReturnCodeHandler = new InUIThreadHandler();
		mAction = getIntent().getAction();
		extras = getIntent().getExtras();
		mQuery = new AQuery(this);
		initView();
		if(builtservice != null){
			userName = builtservice.getUserName();
			authKey = builtservice.getAuthKey();
		}
		if (extras != null && extras.get(EXTRA_ITEM) != null){
			mProduct = (ListItemEntity) extras.get(EXTRA_ITEM);
			if (mBuiltinServiceManager != null){
				mBuiltinServiceManager.saveProductID(mProduct.getRemoteId(), System.currentTimeMillis());	
			}
			NotInPCodes = mProduct.getPcode()+"";
			updateDataUI();
			loadData();
		}

		//tang view
		ClassifiedCore.getInstance(IADetailProductActivity.this).taskUpdateViewProduct(mListener,mProduct.getPcode()+"");
	}	

	private void updateDataUI(){
		if (mProduct != null){
			tvTitle.setText(mProduct.getCategoryName());
			productId = mProduct.getRemoteId();
			tv_name_product.setText(mProduct.getTitle());
			tittleProduct = mProduct.getTitle();
			sellerEmail = mProduct.getSellerEmail();
			sellerPhome =mProduct.getSellerPhone();
			sellerUserName = mProduct.getSellerUsername(); 

			if (mProduct.getLisPromotionHomeEntities() != null){
				discount = mProduct.getLisPromotionHomeEntities().getDiscount();
				try {
					discountValue = Integer.parseInt(discount);
				} catch (Exception e) {}
				if (discountValue >0){
					String new_price = StringUtilities.convertNewPrice(mProduct.getPrice(), discountValue);
					if (!TextUtils.isEmpty(new_price) && !new_price.equals("")) {
						tv_price_product.setText(new_price + " VND");
					}else{
						tv_price_product.setText(IADetailProductActivity.this.getResources().getString(R.string.contact));
					}
				}else{
					if (mProduct.getPrice() != null && mProduct.getPrice().length() > 0 && !mProduct.getPrice().equals("0")&& !mProduct.getPrice().equals("null")) {
						tv_price_product.setText(StringUtilities.convertPrice(mProduct.getPrice())+ " VND");
					}else{
						tv_price_product.setText(IADetailProductActivity.this.getResources().getString(R.string.contact));
					}
				}

			}else{

				if (mProduct.getPrice() != null && mProduct.getPrice().length() > 0 && !mProduct.getPrice().equals("0") && !mProduct.getPrice().equals("null")) {
					tv_price_product.setText(StringUtilities.convertPrice(mProduct.getPrice())+ " VND");
				}else{
					tv_price_product.setText(IADetailProductActivity.this.getResources().getString(R.string.contact));

				}
			}
			tv_product_type.setText(mProduct.getState());

			hightLightAdapter = new ViewPagerAdapterProduct(IADetailProductActivity.this, mProduct.getCoverPicture(),discount,mQuery);
			mViewPager.setAdapter(hightLightAdapter);
			if (mProduct.getCoverPicture().size()  < 2 ) {
				arrow_right_product.setVisibility(View.GONE);
				arrow_left_product.setVisibility(View.GONE);
			}

		}
		Other_product_Adapter = new HomeProductAdapter(IADetailProductActivity.this,arrOtherProduct,mQuery);
		hListView_Other.setAdapter(Other_product_Adapter);
		Product_by_Seller_Adapter = new HomeProductAdapter(IADetailProductActivity.this, arrBySellerProduct,mQuery);	
		hList_product_by_seller.setAdapter(Product_by_Seller_Adapter);
		mBar.setVisibility(View.GONE);
	}


	private void reSizeViewpager(){
		if (mViewPager != null){
			ViewTreeObserver treeObserver = mViewPager.getViewTreeObserver();
			treeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

				@SuppressWarnings("deprecation")
				@Override
				public void onGlobalLayout() {
					int height = (int)((MainApplication.screenWidth*5)/8.0f);
					LayoutParams params = new LayoutParams(ViewPager.LayoutParams.MATCH_PARENT,height); 
					mViewPager.setLayoutParams(params);
					mViewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
				}
			});
		}
	}

	protected void showMessageToast(final String message) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(IADetailProductActivity.this,message, Toast.LENGTH_SHORT).show();
			}
		});
	}
	private void initView() {	
		btnBack =(ImageButton)findViewById(R.id.btn_sub_title_back);
		tvTitle = (TextView)findViewById(R.id.tv_sub_title_text);
		btnSearchGlobal = (ImageView)findViewById(R.id.btn_sub_title_search_home);

		btnBack.setOnClickListener(this);
		btnSearchGlobal.setOnClickListener(this);

		mScrollView = (ScrollView)findViewById(R.id.scroll_detail_product);
		tv_name_product = (TextView) findViewById(R.id.tv_name_product);
		tvreportViolations = (TextView) findViewById(R.id.report_violations);
		tvreportViolations.setOnClickListener(this);
		tv_interested_product = (TextView) findViewById(R.id.tv_interest_product);
		tv_interested_product.setOnClickListener(this);
		mViewPager = (ViewPager)findViewById(R.id.viewpager_product);
		mViewPager.setOnPageChangeListener(this);
		arrow_left_product = (ImageView) findViewById(R.id.arrow_left_product);
		arrow_left_product.setOnClickListener(this);
		arrow_right_product = (ImageView) findViewById(R.id.arrow_right_product);
		arrow_right_product.setOnClickListener(this);
		mBar = (ProgressBar)findViewById(R.id.pBar_product_detail);
		v_rate_feedback_shop = (View) findViewById(R.id.v_rate_feedback_shop);
		tv_rate_feedback_shop = (TextView) findViewById(R.id.tv_rate_feedback_shop);
		/*
		 * init info price product
		 */
		tv_price_product = (TextView) findViewById(R.id.tv_price_product);
		tv_product_type = (TextView)findViewById(R.id.tv_product_type);

		/*
		 * init info product
		 */
		btn_share= (Button)findViewById(R.id.btn_share_product);

		btn_info_product = (Button)findViewById(R.id.btn_info_product);

		tv_desc_info = (WebView)findViewById(R.id.tv_des_info);


		btn_share.setOnClickListener(this);
		btn_info_product.setOnClickListener(this);


		/*
		 * Other product
		 */

		tv_other_product = (TextView)findViewById(R.id.tv_view_other_product);
		pBar_Other = (ProgressBar)findViewById(R.id.pBar_other_product);
		hListView_Other = (HListView)findViewById(R.id.hl_pager_other_product);
		footerView =  ((LayoutInflater)IADetailProductActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
		hListView_Other.addFooterView(footerView);
		pb_pg_load_bottom = (ProgressBar) footerView.findViewById(R.id.pg_load_bottom);
		hListView_Other.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsHListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					if(pageNumberOtherProduct < pageCount){
						pageNumberOtherProduct++;
						NotInPCodes = mProduct.getPcode()+"";

						ClassifiedCore.getInstance(IADetailProductActivity.this).taskGetAndroidProductType(mListener, mProduct.getCategoryId(), 
								mProduct.getGuaranteeStoreID() + "", "", PAGE_LIMIT, pageNumberOtherProduct, PRODUCT_KEY, false, NotInPCodes);
						pb_pg_load_bottom.setVisibility(View.VISIBLE);
					}
					break;
				}
				if(pageNumberOtherProduct < pageCount){
					pageNumberOtherProduct++;
				}
				NotInPCodes = mProduct.getPcode()+"";

				ClassifiedCore.getInstance(IADetailProductActivity.this).taskGetAndroidProductType(mListener, mProduct.getCategoryId(), 
						mProduct.getGuaranteeStoreID() + "", "", PAGE_LIMIT, pageNumberOtherProduct, PRODUCT_KEY, false, NotInPCodes);
			}
			@Override
			public void onScroll(AbsHListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {}
		});
		tv_other_product.setOnClickListener(this);

		/*
		 * Rating and Comment
		 */
		rating_Product = (RatingBar)findViewById(R.id.ratingbar_product);
		tv_Sum_rating = (TextView)findViewById(R.id.tv_sum_rating_product);
		lvRating = (ListView)findViewById(R.id.lv_rating_product);

		lvComment = (ListView)findViewById(R.id.lv_comment_product);
		btn_view_all_cmt = (Button)findViewById(R.id.btn_view_all_comment);
		btn_view_all_cmt.setOnClickListener(this);

		rating_feedback = (RatingBar)findViewById(R.id.rating_freedback_product);
		edt_title_feedback = (EditText)findViewById(R.id.edt_tittle_feedback);
		edt_content_feedback=(EditText)findViewById(R.id.edt_content_feedback);
		btn_send_feedback =(Button)findViewById(R.id.btn_send_feedback);
		btn_send_feedback.setOnClickListener(this);
		edt_content_feedback.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
					ValidateFeedback();
				}
				return false;
			}
		});

		/*
		 * Product by Seller
		 */
		tv_view_product_by_seller = (TextView)findViewById(R.id.tv_view_product_by_seller);
		pBar_product_by_seller = (ProgressBar)findViewById(R.id.pBar_product_by_seller);
		hList_product_by_seller =(HListView)findViewById(R.id.hl_pager_product_by_seller);
		tv_view_product_by_seller.setOnClickListener(this);

		/*
		 * Floating Bar UI
		 */
		llFloatingbar = (LinearLayout)findViewById(R.id.ll_floating_bar_detail_product);
		ll_fb_phone = (LinearLayout)findViewById(R.id.ll_fb_phone);
		ll_fb_chat = (LinearLayout)findViewById(R.id.ll_fb_chat);
		ll_fb_email = (LinearLayout)findViewById(R.id.ll_fb_email);

		ll_fb_phone.setOnClickListener(this);
		ll_fb_chat.setOnClickListener(this);
		ll_fb_email.setOnClickListener(this);


		llFloatingbar.setVisibility(View.VISIBLE);
		mAnimation = AnimationUtils.loadAnimation(this, R.anim.animation_show_fb);
		mAnimation1 = AnimationUtils.loadAnimation(this, R.anim.animation_hide_fb);
		mAnimation1.setAnimationListener(new Animation.AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) { }

			@Override
			public void onAnimationRepeat(Animation animation) { }

			@Override
			public void onAnimationEnd(Animation animation) {
				llFloatingbar.setVisibility(View.GONE);
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						if (llFloatingbar.getVisibility() == View.GONE && isFocus == true){
							llFloatingbar.startAnimation(mAnimation);
							llFloatingbar.setVisibility(View.VISIBLE);
						}
					}
				}, 4500);
			}
		});
		mScrollView.setOnTouchListener(this);
		mScrollView.requestDisallowInterceptTouchEvent(true);

	}


	@Override
	protected void onResume() {
		reSizeViewpager();
		super.onResume();
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(this);
		builtservice = mBuiltinServiceManager.getBuitinService();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}
	@Override
	protected void onStop() {
		super.onStop();
	}
	private void setErrorMsg(String msg,EditText viewId)
	{
		int ecolor = Color.RED; // whatever color you want
		String estring = msg;
		ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
		SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
		ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
		viewId.setError(ssbuilder);

	}

	private void ValidateFeedback() {
		if (builtservice == null){
			LoginActivity.actionLaunch(IADetailProductActivity.this);
			return;
		}
		if (rating_feedback.getRating() == 0 && edt_content_feedback.getText().toString().equals("") ){
			Toast.makeText(IADetailProductActivity.this,this.getString(R.string.error_rating_comment), Toast.LENGTH_SHORT).show();
			rating_feedback.requestFocus();
			return;
		}

		ClassifiedCore.getInstance(getApplication()).taskComment(mListener,mProduct.getRemoteId(),edt_title_feedback.getText().toString(),
				edt_content_feedback.getText().toString(),builtservice.getUserName(), (int) rating_feedback.getRating(),PRODUCT_KEY, commented, Utils.getCurrentTime());
		mBar.setVisibility(View.VISIBLE);

	} 

	private void sendEmail(){
		String subject = "Keeto - " + "<" + tittleProduct + ">";
		Intent email = new Intent(Intent.ACTION_SEND);
		email.putExtra(Intent.EXTRA_EMAIL, new String[] { sellerEmail });
		email.putExtra(Intent.EXTRA_SUBJECT, subject);
		email.putExtra(Intent.EXTRA_TEXT, "");

		email.setType("message/rfc822");
		startActivity(Intent.createChooser(email,this.getResources().getString(R.string.option_send_mail)));
	}

	private void sendSMS(String numPhone) {
		Intent smsIntent = new Intent(Intent.ACTION_VIEW);
		smsIntent.setType("vnd.android-dir/mms-sms");
		smsIntent.putExtra("address", numPhone+"");
		smsIntent.putExtra("sms_body","");
		startActivity(smsIntent);
	}

	private void reportViolations() {
		ReportViolations dialog = new ReportViolations(IADetailProductActivity.this, mProduct.getRemoteId());
		dialog.show();
	}
	private void phoneStore(){
		Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + sellerPhome));
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_sub_title_back:
			this.finish();
			break;
		case R.id.arrow_left_product:
			mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1); 
			arrow_right_product.setVisibility(View.VISIBLE);
			break;
		case R.id.arrow_right_product:
			mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1); 
			if (mViewPager.getCurrentItem() == 0) {
				arrow_right_product.setVisibility(View.GONE);
			}
			arrow_left_product.setVisibility(View.VISIBLE);
			break;

		case R.id.btn_share_product:
			Intent sendIntent = new Intent();
			sendIntent.setAction(Intent.ACTION_SEND);
			sendIntent.putExtra(Intent.EXTRA_EMAIL,new String[] {mProduct.getSellerEmail()});
			sendIntent.putExtra(Intent.EXTRA_SUBJECT,mProduct.getTitle()+" - KeeTo");
			if(!mProduct.getDownloadUrl().equals(null)){
				sendIntent.putExtra(Intent.EXTRA_TEXT,mProduct.getLink());
			} else {
				sendIntent.putExtra(Intent.EXTRA_TEXT,"null");
			}
			sendIntent.setType("text/plain");
			startActivity(sendIntent);
			break;
		case R.id.tv_interest_product:
			if(tv_interested_product.isSelected()){
				sendInterestProduct(false);
			} else {
				sendInterestProduct(true);
			}
			break;
		case R.id.report_violations:
			reportViolations();
			break;

		case R.id.btn_view_all_comment:
			if (commentProductAdapter!= null && commentProductAdapter.getCount()!= 0){
				CommentProductDetailActivity.actionLauch(IADetailProductActivity.this, mProduct.getRemoteId());
			}
			break;
		case R.id.tv_view_other_product:
			ListCateproductActivity.actionLaunchCate(IADetailProductActivity.this,IADetailProductActivity.this.getResources().getString(R.string.other_products), mProduct.getCategoryId(), mProduct.getGuaranteeStoreID(), mProduct.getPcode()+"");//();
			break;
		case R.id.tv_view_product_by_seller:
			ListCateproductActivity.actionLaunchViewAllSameCost(IADetailProductActivity.this, IADetailProductActivity.this.getResources().getString(R.string.product_people_sale), getCost(), mProduct.getCategoryParentID(),  mProduct.getGuaranteeStoreID(), mProduct.getPcode()+"");
			break;
		case R.id.btn_send_feedback:
			ValidateFeedback();
			break;
		case R.id.ll_fb_phone:
			phoneStore();			
			break;
		case R.id.ll_fb_chat:
			sendSMS(sellerPhome);
			break;
		case R.id.ll_fb_email:
			sendEmail();
			break;
		case R.id.btn_sub_title_search_home:
			ProductsActivity.actionSearchGlobal(this);
			break;

		default:
			break;
		}
	}


	class DetailListener extends ClassifiedListener {

		@Override
		public void finishGetAndroidProductType(final int returnCode,
				final ArrayList<ListItemEntity> listProductType, final int PageCount) {
			// TODO Auto-generated method stub
			super.finishGetAndroidProductType(returnCode, listProductType, PageCount);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (returnCode == IProtocol.STATUS_CODE_OK_200){
						pageCount = PageCount;
						if (listProductType!= null){
							//							arrOtherProduct.clear();
							arrOtherProduct.addAll(listProductType);
							Other_product_Adapter.notifyDataSetChanged();
						}
					}
					pBar_Other.setVisibility(View.GONE);
					mBar.setVisibility(View.GONE);
					pb_pg_load_bottom.setVisibility(View.GONE);

				}
			});
		} 
		@Override
		public void finishGetAndroidInterestShop(final int returnCode, final boolean isInterest) {
			super.finishGetAndroidInterestShop(returnCode, isInterest);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						if(isInterest == true){
							tv_interested_product.setSelected(true);
						}else{
							tv_interested_product.setSelected(false);
						}
					}else{
						mReturnCodeHandler.takeActionByReturnCode(IADetailProductActivity.this, returnCode, true);
					}
					mBar.setVisibility(View.GONE);
				}
			});
		}
		@Override
		public void finishSendAndroidInterestShop(final int returnCode) {
			super.finishSendAndroidInterestShop(returnCode);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mBar.setVisibility(View.GONE);
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						if (tv_interested_product.isSelected()){
							tv_interested_product.setSelected(false);
						}else{
							tv_interested_product.setSelected(true);
						}
					}else{
						mReturnCodeHandler.takeActionByReturnCode(IADetailProductActivity.this, returnCode, true);
					}

				}
			});
		}

		@Override
		public void finishGetAndroidProductSameCost(final int returnCode,
				final ArrayList<ListItemEntity> listProductType, final int PageCount) {
			// TODO Auto-generated method stub
			super.finishGetAndroidProductType(returnCode, listProductType, PageCount);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					pBar_product_by_seller.setVisibility(View.GONE);			
					if (returnCode == IProtocol.STATUS_CODE_OK_200){
						pageCount = PageCount;
						if (listProductType!= null){
							//							arrOtherProduct.clear();
							//							arrOtherProduct.addAll(listProductType);
							//							Other_product_Adapter.notifyDataSetChanged();
							arrBySellerProduct.addAll(listProductType);
							Product_by_Seller_Adapter.notifyDataSetChanged();
						}
					}
					pBar_Other.setVisibility(View.GONE);
					mBar.setVisibility(View.GONE);
					pb_pg_load_bottom.setVisibility(View.GONE);

				}
			});
		}

		@Override
		public void finishGetCommentProduct(final int returnCode, final String description,
				final ArrayList<CommentEntity> listComment, final RatingInfo ratingInfo,
				final ArrayList<RatingUserEntity> arrRating) {
			// TODO Auto-generated method stub
			super.finishGetCommentProduct(returnCode, description, listComment,
					ratingInfo, arrRating);
			runOnUiThread(new Runnable() {
				public void run() {
					if(returnCode == IProtocol.STATUS_CODE_OK_200){
						if (listComment != null){
							if(listComment.size() == 0){
								v_rate_feedback_shop.setVisibility(View.GONE);
								tv_rate_feedback_shop.setVisibility(View.GONE);
								btn_view_all_cmt.setVisibility(View.GONE);
							} else {
								v_rate_feedback_shop.setVisibility(View.VISIBLE);
								tv_rate_feedback_shop.setVisibility(View.VISIBLE);

								for (int i = 0; i < listComment.size(); i++) {
									if( !TextUtils.isEmpty(listComment.get(i).getCommentTitle())
											&&!TextUtils.isEmpty(listComment.get(i).getCommentContent())
											&&!listComment.get(i).getCommentTitle().equals("null") 
											&& !listComment.get(i).getCommentContent().equals("null")){
										commentList_total.add(listComment.get(i));
									}
								}
								commentList.clear();
								if (commentList_total != null&& commentList_total.size() <= 3) {
									
									for (int k = 0; k < commentList_total.size(); k++) {
										commentList.add(commentList_total.get(k));
									}
								} else {
									btn_view_all_cmt.setVisibility(View.VISIBLE);
									for (int i = 0; i < 3; i++) {
										commentList.add(commentList_total.get(i));
									}
								}

								commentProductAdapter = new CommentViewAdapter(commentList, IADetailProductActivity.this,mQuery);
								lvComment.setAdapter(commentProductAdapter);
								if (commentList.size() <3){
									UtilityListView.setListViewHeightBasedOnChildrenforListTest(IADetailProductActivity.this, lvComment);
								}else{
									UtilityListView.setListViewHeightBasedOnChildrenforWarranty(IADetailProductActivity.this, lvComment);
								}
							}
						}
						if (arrRating != null){
							if(builtservice != null && arrRating.size()>0) {
								for (int i = 0; i < arrRating.size(); i++) {
									if(arrRating.get(i).getUserName().equals(builtservice.getUserName())){
										if (arrRating.get(i).getValue().equals("Excellent")){
											rating_feedback.setRating(5);
										}else if (arrRating.get(i).getValue().equals("VeryGood")){
											rating_feedback.setRating(4);
										}else if (arrRating.get(i).getValue().equals("VeryGood")){
											rating_feedback.setRating(3);
										}else if (arrRating.get(i).getValue().equals("Poor")){
											rating_feedback.setRating(2);
										}else if (arrRating.get(i).getValue().equals("Terrible")){
											rating_feedback.setRating(1);
										}
										rating_feedback.setIsIndicator(true);  
										commented = true;
										break;
									}else{
										commented = false;
										rating_feedback.setIsIndicator(false);
									}
								}
							}
						}
						if (ratingInfo != null){
							rating_Product.setRating(ratingInfo.getRating());
							int total = ratingInfo.getTotalCount();
							float rating1 = 0;
							float rating2 = 0;
							float rating3 = 0;
							float rating4 = 0;
							float rating5 = 0;
							int exc, good, aver, poor, teri;
							exc = ratingInfo.getExcellent();
							good = ratingInfo.getVerygood();
							aver = ratingInfo.getAverage();
							poor = ratingInfo.getPoor();
							teri = ratingInfo.getTerrible();
							if (total > 0) {
								rating1 = (exc * 100) / total;
								rating2 = (good * 100) / total;
								rating3 = (aver * 100) / total;
								rating4 = (poor * 100) / total;
								rating5 = (teri * 100) / total;
							}
							tv_Sum_rating.setText("(" + total + ")");
							ratingList.clear();
							ratingList.add(new RatingProduct(getResources()
									.getString(R.string.ia_product_five_star),
									rating1, "(" + exc + ")"));
							ratingList.add(new RatingProduct(getResources()
									.getString(R.string.ia_product_four_star),
									rating2, "(" + good + ")"));
							ratingList.add(new RatingProduct(getResources()
									.getString(R.string.ia_product_three_star),
									rating3, "(" + aver + ")"));
							ratingList.add(new RatingProduct(getResources()
									.getString(R.string.ia_product_two_star),
									rating4, "(" + poor + ")"));
							ratingList.add(new RatingProduct(getResources()
									.getString(R.string.ia_product_one_star),
									rating5, "(" + teri + ")"));
							ratingProductAdapter = new RatingProductAdapter(
									ratingList, IADetailProductActivity.this);
							lvRating.setAdapter(ratingProductAdapter);
							UtilityListView.setListViewHeightBasedOnChildrenforList(IADetailProductActivity.this, lvRating);

						}

						description.replace("style=\"width: 800px;", "style=\"width: 400px");
						tv_desc_info.loadDataWithBaseURL(null, description,"text/html", "UTF-8", null);//setText(Html.fromHtml(description_replace));
					}else {
						mReturnCodeHandler.takeActionByReturnCode(IADetailProductActivity.this, returnCode, true);
					}
					mBar.setVisibility(View.GONE);

				}
			});
		} 
		@Override
		public void finishIAComment(final int returnCode, String resultMsg) {
			super.finishIAComment(returnCode, resultMsg);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mBar.setVisibility(View.GONE);
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						String message = IADetailProductActivity.this.getResources().getString(R.string.text_successful);
						showMessageToast(message);
						edt_title_feedback.setText("");
						edt_content_feedback.setText("");
						rating_feedback.setRating(0);
						ClassifiedCore.getInstance(IADetailProductActivity.this).taskGetCommentDetailProduct(mListener,  mProduct.getRemoteId());
					} else {
						mReturnCodeHandler.takeActionByReturnCode(IADetailProductActivity.this, returnCode, true);
						showMessageToast(IADetailProductActivity.this.getResources().getString(R.string.error_send_comment));
					}
					loadData();
				}
			});
		}
	}

	private void loadData() {
		pBar_Other.setVisibility(View.VISIBLE);
		mBar.setVisibility(View.VISIBLE);
		NotInPCodes = mProduct.getPcode()+"";

		ClassifiedCore.getInstance(IADetailProductActivity.this).taskGetAndroidProductType(mListener, mProduct.getCategoryId(), 
				mProduct.getGuaranteeStoreID() + "", "", PAGE_LIMIT, pageNumberOtherProduct, PRODUCT_KEY, false, NotInPCodes);
		ClassifiedCore.getInstance(IADetailProductActivity.this).taskGetAndroidProductSameCost(mListener, mProduct.getCategoryId(), 
				mProduct.getGuaranteeStoreID() + "", "", PAGE_LIMIT, pageNumberOtherProduct, PRODUCT_KEY, false, NotInPCodes,getCost());

		ClassifiedCore.getInstance(IADetailProductActivity.this).taskGetCommentDetailProduct(mListener,  mProduct.getRemoteId());
		getInterestShop();		

	}


	private void getInterestShop(){
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if(builtservice != null){
					userName = builtservice.getUserName();
				}
				if (userName!= null && !userName.equals("")){
					ClassifiedCore.getInstance(IADetailProductActivity.this).taskGetAndroidInterest(mListener, mProduct.getRemoteId(), userName, PRODUCT_KEY);
				}else{
					tv_interested_product.setSelected(false);
				}
			}
		});
	}


	@Override
	public void onPageScrollStateChanged(int position) {
		if (position == (mProduct.getCoverPicture().size() - 1)) {
			arrow_left_product.setVisibility(View.VISIBLE);
			arrow_right_product.setVisibility(View.GONE);
		} else if (position == 0) {
			arrow_left_product.setVisibility(View.GONE);
			arrow_right_product.setVisibility(View.VISIBLE);
		} else {
			arrow_left_product.setVisibility(View.VISIBLE);
			arrow_right_product.setVisibility(View.VISIBLE);
		}
	}
	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}
	@Override
	public void onPageSelected(int arg0) {

	}

	private void sendInterestProduct(final boolean isinterest) {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				mBuiltinServiceManager = BuiltinServiceManager.getInstance(IADetailProductActivity.this);
				builtservice = mBuiltinServiceManager.getBuitinService();
				if (!builtservice.getUserName().equals("") && !builtservice.getAuthKey().equals("")) {  
					mBar.setVisibility(View.VISIBLE);
					if (isinterest == true) {
						ClassifiedCore.getInstance(getApplication()).taskSendAndroidInterest(mListener, productId, builtservice.getUserName(), 1, PRODUCT_KEY, builtservice.getAuthKey());
					} else {
						ClassifiedCore.getInstance(getApplication()).taskSendAndroidInterest(mListener, productId, builtservice.getUserName(), 1, PRODUCT_KEY, builtservice.getAuthKey());
					}
				} else {
					showMessageToast(IADetailProductActivity.this.getResources().getString(R.string.do_login));
				}
			}
		});
	}
	class ProgressHandler extends Handler {

		public void showProgressDialog(final String message) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					mProgressDialog = new ProgressDialog(IADetailProductActivity.this);
					mProgressDialog.setMessage(message);
					mProgressDialog.show();
				}
			});
		}

		public void dismissProgressDialog() {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					if (mProgressDialog != null && mProgressDialog.isShowing()) {
						mProgressDialog.dismiss();
					}
				}
			});
		}
	}
	private Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if(hightLightAdapter != null){
				if(position_img_product > hightLightAdapter.getCount()){
				} else {
					position_img_product = position_img_product + 1;
				}
				mViewPager.setCurrentItem(position_img_product, true);
			}
			handler_img_product.postDelayed(runnable, 3000);
		}
	};

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_MOVE){
			moveY = event.getRawY();
			if (moveY > oldTouchValue && (llFloatingbar.getVisibility() == View.VISIBLE) ){
				llFloatingbar.startAnimation(mAnimation1);
			}else if (moveY <= oldTouchValue && (llFloatingbar.getVisibility() == View.GONE) && isFocus != true ){
				llFloatingbar.setVisibility(View.VISIBLE);

				llFloatingbar.startAnimation(mAnimation);
			}
			oldTouchValue = moveY;
		}
		return false;
	}

	private String getCost(){
		String[] cost = null;
		String price="";
		if(tv_price_product.getText().toString().contains("VND")){
			cost=tv_price_product.getText().toString().split(" ");
			price=cost[0].replaceAll(",",""); 
		}
		else{
			price="";
		}

		return price ;

	} 
	private void hidekeyboard(){
		InputMethodManager imm = (InputMethodManager)getSystemService( Context.INPUT_METHOD_SERVICE);
		View view = this.getCurrentFocus();
		imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(isTaskRoot()){

			long triggerSize = 3000000; 
			long targetSize = 2000000;      
			AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
		}
	}
}
